package blue.web.dao.service;

import blue.tools.constants.BlueContants;
import blue.dao.base.BaseMapper;
import blue.commons.models.KeyValue;
import blue.erp.model.BlueClass;
import blue.erp.model.SysUser;
import blue.splitclass.dao.SplitClassLayerStudentMapper;
import blue.splitclass.model.SplitClassLayerStudent;
import blue.splitclass.model.SplitClassLayerStudentExample;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SplitClassLayerStudentService extends BaseService {

    @Autowired
    private SplitClassLayerStudentMapper splitClassLayerCourseMapper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private BlueCourseService blueCourseService;

    @Autowired
    private BlueClassService blueClassService;

    @Autowired
    private SplitClassLayerCourseService splitClassLayerCourseService;

    private static final String classLayerStudentClassPrefix="classLayerStudentClassPrefix";
    private static final String classLayerStudentCoursePrefix="classLayerStudentCoursePrefix";
    private static final String classLayerStudentLayerPrefix="classLayerStudentLayerPrefix";
    private static final String classLayerCourseSelectedPrefix="classLayerCourseSelectedPrefix";

    public int deleteByTask(SplitClassLayerStudent splitClassLayerStudent) {

        if(splitClassLayerStudent==null || splitClassLayerStudent.getTaskId()==null || splitClassLayerStudent.getSchoolid()==null){
            return 0;
        }
        SplitClassLayerStudentExample example=new SplitClassLayerStudentExample();
        example.createCriteria().andTaskIdEqualTo(splitClassLayerStudent.getTaskId()).andSchoolidEqualTo(splitClassLayerStudent.getSchoolid());
        clearCache(splitClassLayerStudent.getSchoolid(),splitClassLayerStudent.getTaskId());
        return this.getBaseMapper().deleteByExample(example);
    }


    public int save(SplitClassLayerStudent record) {
        if(record==null || record.getTaskId()==null){
            return 0;
        }

        SplitClassLayerStudentExample example=new SplitClassLayerStudentExample();
        SplitClassLayerStudentExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(record.getSchoolid());

        if(record.getTaskId()!=null){
            criteria.andTaskIdEqualTo(record.getTaskId());
        }
        if(record.getUserid()!=null){
            criteria.andUseridEqualTo(record.getUserid());
        }

        return this.baseSave(record,example);

    }

    public int saveByExcel(List<SplitClassLayerStudent> splitClassLayerStudentList,Long taskId,Long schoolId){
        if(CollectionUtils.isEmpty(splitClassLayerStudentList) || schoolId==null || taskId==null || taskId<=0){
            return 0;
        }
        int result=0;
        //过滤需要缓存的数据
        HashMap classMap=new HashMap();
        HashMap courseMap=new HashMap();
        HashMap layerMap=new HashMap();

        List classList=new LinkedList();
        List courseList=new LinkedList();
        List layerList=new LinkedList();

        //将选课结果同步到分班分层缓存中
//        Set<String> courseSelectedKeys=redisService.getVagueKeys(String.format("%s_%s_%s",BlueContants.prefix_selected_oneSubject_total,schoolId,taskId));
//        if(CollectionUtils.isNotEmpty(courseSelectedKeys)){
//            for(String key:courseSelectedKeys){
//                Set keyValues=redisService.getFromSet(key);
//                redisService.add2Set(key.replaceAll(BlueContants.prefix_selected_oneSubject_total,classLayerCourseSelectedPrefix),keyValues);
//            }
//        }

        for(SplitClassLayerStudent splitClassLayerStudent:splitClassLayerStudentList){
            SysUser sysUser=new SysUser();
            sysUser.setUserno(splitClassLayerStudent.getUserno());
            sysUser.setSchoolid(schoolId);
            List<SysUser> userExtendList=sysUserService.select(sysUser);
            if(CollectionUtils.isEmpty(userExtendList) || userExtendList.size()!=1 || StringUtils.isBlank(splitClassLayerStudent.getLayerInfo())){
                continue;
            }
            splitClassLayerStudent.setUsername(userExtendList.get(0).getRealName());
            splitClassLayerStudent.setClassId(Long.decode(userExtendList.get(0).getClassIds()));
            splitClassLayerStudent.setSchoolid(schoolId);
            splitClassLayerStudent.setTaskId(taskId);
            splitClassLayerStudent.setUserid(userExtendList.get(0).getId());
            result+=this.save(splitClassLayerStudent);

            //缓存数据
            if(classMap.get(splitClassLayerStudent.getClassId())==null){
                classMap.put(splitClassLayerStudent.getClassId(),userExtendList.get(0).getClasses().get(0).getValue());
                classList.add(new KeyValue(splitClassLayerStudent.getClassId(),userExtendList.get(0).getClasses().get(0).getValue()));
            }
            JSONObject layerObject=JSONObject.parseObject(splitClassLayerStudent.getLayerInfo());
            for(String courseName:layerObject.keySet()){
               if(courseMap.get(courseName)==null){
                   courseMap.put(courseName,courseName);
                   courseList.add(new KeyValue(courseName,courseName));
               }
               if(layerMap.get(layerObject.get(courseName))==null){
                   layerMap.put(layerObject.get(courseName),layerObject.get(courseName));
                   layerList.add(new KeyValue(layerObject.get(courseName),layerObject.get(courseName)));
               }
//               if(layerObject.get(courseName)!=null){
//                   Long redisResult=redisService.add2Set(String.format("%s_%s_%s_%s_%s",BlueContants.prefix_selected_oneSubject_total,schoolId,taskId,courseName,layerObject.get(courseName)),splitClassLayerStudent.getUserid().toString());
//                   if(redisResult!=null && redisResult>0){
//                       redisService.remove2Set(String.format("%s_%s_%s_%s",BlueContants.prefix_selected_oneSubject_total,sysUser.getSchoolid(),taskId,
//                               blueCourseService.selectedByName(courseName,null,schoolId,false).getId()),splitClassLayerStudent.getUserid().toString());
//                   }
//               }
            }

        }

        redisService.setValue(String.format("%s_%s_%s",classLayerStudentClassPrefix,schoolId,taskId),JSONObject.toJSONString(classList),BlueContants.month);
        redisService.setValue(String.format("%s_%s_%s",classLayerStudentCoursePrefix,schoolId,taskId),JSONObject.toJSONString(courseList),BlueContants.month);
        redisService.setValue(String.format("%s_%s_%s",classLayerStudentLayerPrefix,schoolId,taskId),JSONObject.toJSONString(layerList),BlueContants.month);
        splitClassLayerCourseService.clearCache(schoolId,taskId);
        return result;
    }

    public Map getGroupInfo(Long taskId,Long schoolId){
        HashMap result=new HashMap();
        Object classList=redisService.getValue(String.format("%s_%s_%s",classLayerStudentClassPrefix,schoolId,taskId));
        if(classList!=null){
            redisService.setValue(String.format("%s_%s_%s",classLayerStudentClassPrefix,schoolId,taskId), (String) classList,BlueContants.month);
        }
        result.put("classList",classList);

        Object courseList=redisService.getValue(String.format("%s_%s_%s",classLayerStudentCoursePrefix,schoolId,taskId));
        if(courseList!=null){
            redisService.setValue(String.format("%s_%s_%s",classLayerStudentCoursePrefix,schoolId,taskId), (String) courseList,BlueContants.month);
        }
        result.put("courseList",courseList);

        Object layerList=redisService.getValue(String.format("%s_%s_%s",classLayerStudentLayerPrefix,schoolId,taskId));
        if(layerList!=null){
            redisService.setValue(String.format("%s_%s_%s",classLayerStudentLayerPrefix,schoolId,taskId), (String) layerList,BlueContants.month);
        }
        result.put("layerList",layerList);

        return result;
    }

    public List<SplitClassLayerStudent> selectByObject(SplitClassLayerStudent record){

        if(record.getTaskId()==null){
            return null;
        }

        SplitClassLayerStudentExample example=new SplitClassLayerStudentExample();
        SplitClassLayerStudentExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(record.getSchoolid()).andTaskIdEqualTo(record.getTaskId());

        if(record.getId()!=null){
            criteria.andIdEqualTo(record.getId());
        }

        return this.select(example);
    }


    public List<SplitClassLayerStudent> selectByTaskId(Long taskId,Long schoolId){
        if(taskId==null || schoolId==null){
            return null;
        }
        SplitClassLayerStudent splitClassLayerStudent=new SplitClassLayerStudent();
        splitClassLayerStudent.setTaskId(taskId);
        splitClassLayerStudent.setSchoolid(schoolId);

        return selectByObject(splitClassLayerStudent);
    }

    public List<SplitClassLayerStudent> selectBySearchKey(SplitClassLayerStudent record,String subjectName,String layerName){

        if(record.getTaskId()==null){
            return null;
        }

        SplitClassLayerStudentExample example=new SplitClassLayerStudentExample();
        SplitClassLayerStudentExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(record.getSchoolid()).andTaskIdEqualTo(record.getTaskId());

        if(record.getId()!=null){
            criteria.andIdEqualTo(record.getId());
        }

        if(record.getClassId()!=null && record.getClassId()>0){
            criteria.andClassIdEqualTo(record.getClassId());
        }

        if(StringUtils.isNotBlank(subjectName) && !"-1".equalsIgnoreCase(subjectName)){
            criteria.andLayerInfoLike("%"+subjectName+"%");
        }

        if(StringUtils.isNotBlank(layerName) && !"-1".equalsIgnoreCase(layerName)){
            criteria.andLayerInfoLike("%"+layerName+"%");
        }

        List<SplitClassLayerStudent> result=this.select(example);
        for(SplitClassLayerStudent splitClassLayerStudent:result){
            if(splitClassLayerStudent.getClassId()!=null){
                BlueClass blueClass=blueClassService.selectByPrimaryKey(splitClassLayerStudent.getClassId(),record.getSchoolid(),false);
                if(blueClass!=null){
                    splitClassLayerStudent.setClassName(blueClass.getName());
                }
            }
        }

        return result;
    }



    @Override
    public BaseMapper getBaseMapper() {
        return this.splitClassLayerCourseMapper;
    }

    @Override
    public void clearCache(Long schoolId,Object... extend) {
        redisService.vagueDelete(String.format("%s_%s_%s",classLayerStudentClassPrefix,schoolId,extend[0]));
        redisService.vagueDelete(String.format("%s_%s_%s",classLayerStudentCoursePrefix,schoolId,extend[0]));
        redisService.vagueDelete(String.format("%s_%s_%s",classLayerStudentLayerPrefix,schoolId,extend[0]));
    }
}
